<script setup>

</script>

<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>新增活动</span>
          <el-button @click="goBack" type="primary" plain>返回</el-button>
        </div>
      </template>
      
      <el-form ref="activityRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="form.activityName" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动类型" prop="activityType">
              <el-select v-model="form.activityType" placeholder="请选择活动类型" style="width: 100%" @change="handleActivityTypeChange">
                <el-option label="新人发劵" value="新人发劵" />
                <el-option label="精确发劵" value="精确发劵" />
                <el-option label="邀新赠券" value="邀新赠券" />
                <el-option label="自动赠券" value="自动赠券" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="showActivityScope">
          <el-col :span="12">

            <el-form-item label="活动范围" prop="activityScope">
              <el-select v-model="form.activityScope" placeholder="请选择活动范围" style="width: 100%">
                <el-option label="全部会员" value="全部会员" />
                <el-option label="指定会员" value="指定会员" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="showReceiveFrequency">
          <el-col :span="12">

            <el-form-item label="领取频率" prop="receiveFrequency">
              <el-select v-model="form.receiveFrequency" placeholder="请选择领取频率" style="width: 100%">
                <el-option label="每日一次" value="每日一次" />
                <el-option label="每周一次" value="每周一次" />
                <el-option label="每月一次" value="每月一次" />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="请选择活动开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="请选择活动结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="活动总发放数量" prop="totalIssueCount">
              <el-input-number v-model="form.totalIssueCount" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单日发放数量" prop="dailyIssueCount">
              <el-input-number v-model="form.dailyIssueCount" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单用户限领数量" prop="userLimitCount">
              <el-input-number v-model="form.userLimitCount" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择活动状态" style="width: 100%">
                <el-option label="未开始" value="未开始" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已结束" value="已结束" />
                <el-option label="已暂停" value="已暂停" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="center">赠送配置</el-divider>
        
        <!-- 选择优惠券按钮区域 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="danger" icon="Plus" @click="handleSelectCoupon">选择优惠券</el-button>
          </el-col>
        </el-row>
        
        <!-- 优惠券列表表格 -->
        <el-table :data="couponActivityRelationList" :row-class-name="rowCouponActivityRelationIndex" @selection-change="handleCouponActivityRelationSelectionChange" ref="couponActivityRelation">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="优惠券名称" prop="couponName" width="150">
            <template #default="scope">
              <span>{{ scope.row.couponName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="关联活动名称" prop="activityName" width="150">
            <template #default="scope">
              <el-input 
                v-model="scope.row.activityName" 
                placeholder="关联活动名称"
                :disabled="true"
                title="关联活动名称与活动名称保持一致"
              />
            </template>
          </el-table-column>
          <el-table-column label="赠送数量" prop="issueCount" width="150">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.issueCount" 
                :min="0" 
                style="width: 100%" 
                placeholder="0表示无限制"
                :disabled="true"
                title="赠送数量与活动总发放数量保持一致"
              />
            </template>
          </el-table-column>
          <el-table-column label="是否启用" prop="isEnabled" width="100">
            <template #default="scope">
              <el-switch 
                v-model="scope.row.isEnabled" 
                :active-value="1" 
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100">
            <template #default="scope">
              <el-button link type="danger" icon="Delete" @click="handleDeleteCoupon(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-form-item style="margin-top: 20px;">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="goBack">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 优惠券选择对话框 -->
    <el-dialog :title="'选择优惠券'" v-model="couponSelectOpen" width="800px" append-to-body>
      <el-form :model="couponQueryParams" ref="couponQueryRef" :inline="true" label-width="68px">
        <el-form-item label="优惠券名称" :label-width="'90px'" prop="couponName">
          <el-input
            v-model="couponQueryParams.couponName"
            placeholder="请输入优惠券名称"
            clearable
            @keyup.enter="handleCouponQuery"
          />
        </el-form-item>
        <el-form-item label="使用范围" prop="scopeType">
          <el-select v-model="couponQueryParams.scopeType" placeholder="请选择使用范围" clearable style="width: 200px">
            <el-option label="全品类" value="ALL" />
            <el-option label="指定商品" value="PRODUCT" />
            <el-option label="部分分类" value="CATEGORY" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="couponQueryParams.status" placeholder="请选择状态" clearable style="width: 200px">
            <el-option label="未开始" value="CREATED" />
            <el-option label="进行中" value="ACTIVE" />
            <el-option label="已关闭" value="CLOSED" />
            <el-option label="已过期" value="EXPIRED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleCouponQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetCouponQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="couponLoading" :data="couponList" @selection-change="handleCouponSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="优惠券名称" align="center" prop="couponName" />
        <el-table-column label="类型" align="center" prop="couponType">
          <template #default="scope">
            <el-tag v-if="scope.row.couponType === 'CASH'" type="success">减免现金</el-tag>
            <el-tag v-else-if="scope.row.couponType === 'DISCOUNT'" type="warning">打折</el-tag>
            <span v-else>{{ scope.row.couponType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="面额/折扣" align="center" prop="amount">
          <template #default="scope">
            <span v-if="scope.row.couponType === 'CASH'" style="color: #f56c6c; font-weight: bold;">¥ {{ scope.row.amount }}</span>
            <span v-else-if="scope.row.couponType === 'DISCOUNT'" style="color: #e6a23c; font-weight: bold;">{{ scope.row.amount }}折</span>
            <span v-else>{{ scope.row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用范围" align="center" prop="scopeType">
          <template #default="scope">
            <el-tag v-if="scope.row.scopeType === 'ALL'" type="info">全品类</el-tag>
            <el-tag v-else-if="scope.row.scopeType === 'PRODUCT'" type="warning">指定商品</el-tag>
            <el-tag v-else-if="scope.row.scopeType === 'CATEGORY'" type="success">部分分类</el-tag>
            <span v-else>{{ scope.row.scopeType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'CREATED'" type="primary">未开始</el-tag>
            <el-tag v-else-if="scope.row.status === 'ACTIVE'" type="success">进行中</el-tag>
            <el-tag v-else-if="scope.row.status === 'CLOSED'" type="danger">已关闭</el-tag>
            <el-tag v-else-if="scope.row.status === 'EXPIRED'" type="warning">已过期</el-tag>
            <span v-else>{{ scope.row.status }}</span>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="couponTotal>0"
        :total="couponTotal"
        v-model:page="couponQueryParams.pageNum"
        v-model:limit="couponQueryParams.pageSize"
        @pagination="getCouponList"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmSelectCoupons">确 定</el-button>
          <el-button @click="couponSelectOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AddActivity">
import { addActivity } from "@/api/coupon/activity"
import { listCoupons } from "@/api/coupon/coupons"
import Pagination from "@/components/Pagination/index.vue"

const { proxy } = getCurrentInstance()

const activityRef = ref()
const couponActivityRelationList = ref([])
const checkedCouponActivityRelation = ref([])

// 优惠券选择相关
const couponSelectOpen = ref(false)
const couponLoading = ref(false)
const couponList = ref([])
const couponTotal = ref(0)
const selectedCoupons = ref([])

const data = reactive({
  form: {
    activityName: null,
    activityType: null,
    activityScope: null,
    receiveFrequency: null,
    startTime: null,
    endTime: null,
    totalIssueCount: 0,
    dailyIssueCount: 0,
    userLimitCount: 0,
    status: null
  },
  rules: {
    activityName: [
      { required: true, message: "活动名称不能为空", trigger: "blur" }
    ],
    activityType: [
      { required: true, message: "活动类型不能为空", trigger: "change" }
    ],
    activityScope: [
      { 
        required: true, 
        message: "活动范围不能为空", 
        trigger: "blur",
        validator: (rule, value, callback) => {
          if (form.value.activityType === '精确发劵' && !value) {
            callback(new Error('活动范围不能为空'))
          } else {
            callback()
          }
        }
      }
    ],
    receiveFrequency: [
      { 
        required: true, 
        message: "领取频率不能为空", 
        trigger: "blur",
        validator: (rule, value, callback) => {
          if (form.value.activityType === '自动赠券' && !value) {
            callback(new Error('领取频率不能为空'))
          } else {
            callback()
          }
        }
      }
    ],
    status: [
      { required: true, message: "活动状态不能为空", trigger: "change" }
    ]
  },
  couponQueryParams: {
    pageNum: 1,
    pageSize: 10,
    couponName: null,
    scopeType: null,
    status: null
  }
})

const { form, rules, couponQueryParams } = toRefs(data)

// 计算属性：是否显示活动范围字段
const showActivityScope = computed(() => {
  return form.value.activityType === '精确发劵'
})

// 计算属性：是否显示领取频率字段
const showReceiveFrequency = computed(() => {
  return form.value.activityType === '自动赠券'
})

// 监听活动名称变化，更新已添加的优惠券关联信息
watch(() => form.value.activityName, (newVal) => {
  if (couponActivityRelationList.value.length > 0) {
    couponActivityRelationList.value.forEach(item => {
      item.activityName = newVal || ''
    })
  }
})

// 监听活动总发放数量变化，更新已添加的优惠券关联信息
watch(() => form.value.totalIssueCount, (newVal) => {
  if (couponActivityRelationList.value.length > 0) {
    couponActivityRelationList.value.forEach(item => {
      item.issueCount = newVal || 0
    })
  }
})

// 活动类型变化处理
function handleActivityTypeChange() {
  // 当活动类型改变时，清空相关字段
  if (form.value.activityType !== '精确发劵') {
    form.value.activityScope = null
  }
  if (form.value.activityType !== '自动赠券') {
    form.value.receiveFrequency = null
  }
}

// 返回按钮
function goBack() {
  proxy.$router.go(-1)
}

// 券活动与券的关联序号
function rowCouponActivityRelationIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

// 选择优惠券
function handleSelectCoupon() {
  couponSelectOpen.value = true
  getCouponList()
}

// 获取优惠券列表
function getCouponList() {
  couponLoading.value = true
  listCoupons(couponQueryParams.value).then(response => {
    couponList.value = response.rows
    couponTotal.value = response.total
    couponLoading.value = false
  })
}

// 优惠券查询
function handleCouponQuery() {
  couponQueryParams.value.pageNum = 1
  getCouponList()
}

// 重置优惠券查询
function resetCouponQuery() {
  proxy.resetForm("couponQueryRef")
  handleCouponQuery()
}

// 优惠券选择变化
function handleCouponSelectionChange(selection) {
  selectedCoupons.value = selection
}

// 确认选择优惠券
function confirmSelectCoupons() {
  if (selectedCoupons.value.length === 0) {
    proxy.$modal.msgError("请选择优惠券")
    return
  }
  
  selectedCoupons.value.forEach(coupon => {
    // 检查是否已经添加过
    const exists = couponActivityRelationList.value.find(item => item.couponId === coupon.id)
    if (!exists) {
      const newCoupon = {
        // 根据数据库表结构定义字段
        relationId: null, // 关联记录唯一ID，新增时为空
        activityId: null, // 关联的活动ID，新增时为空
        couponId: coupon.id, // 关联的优惠券ID
        issueCount: form.value.totalIssueCount || 0, // 该优惠券在活动中的发放数量，使用表单的活动总发放数量
        isEnabled: 1, // 是否启用该关联(1:启用;0:禁用)
        activityName: form.value.activityName || '', // 关联活动名称，使用表单的活动名称
        couponName: coupon.couponName, // 关联优惠券名称
        index: couponActivityRelationList.value.length + 1
      }
      couponActivityRelationList.value.push(newCoupon)
    }
  })
  
  couponSelectOpen.value = false
  selectedCoupons.value = []
  proxy.$modal.msgSuccess("优惠券添加成功")
}

// 删除优惠券
function handleDeleteCoupon(row) {
  const index = couponActivityRelationList.value.findIndex(item => item.couponId === row.couponId)
  if (index > -1) {
    couponActivityRelationList.value.splice(index, 1)
    proxy.$modal.msgSuccess("优惠券删除成功")
  }
}

// 券活动与券的关联删除按钮操作
function handleDeleteCouponActivityRelation() {
  if (checkedCouponActivityRelation.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的优惠券")
  } else {
    const couponActivityRelations = couponActivityRelationList.value
    const checkedCouponActivityRelations = checkedCouponActivityRelation.value
    couponActivityRelationList.value = couponActivityRelations.filter(function(item) {
      return checkedCouponActivityRelations.indexOf(item.index) == -1
    })
    proxy.$modal.msgSuccess("批量删除成功")
  }
}

// 复选框选中数据
function handleCouponActivityRelationSelectionChange(selection) {
  checkedCouponActivityRelation.value = selection.map(item => item.index)
}

// 提交按钮
function submitForm() {
  proxy.$refs["activityRef"].validate(valid => {
    if (valid) {
      // 根据活动类型清理不需要的字段
      if (form.value.activityType !== '精确发劵') {
        form.value.activityScope = null
      }
      if (form.value.activityType !== '自动赠券') {
        form.value.receiveFrequency = null
      }
      
      form.value.couponActivityRelationList = couponActivityRelationList.value
      addActivity(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功")
        goBack()
      })
    }
  })
}
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb8 {
  margin-bottom: 8px;
}
</style>